package com.aliyun.heiyu.powermaster.server;

import com.aliyun.heiyu.common.util.LogUtils;
import com.aliyun.heiyu.powermaster.server.agent.AgentManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.grpc.stub.StreamObserver;
import com.aliyun.heiyu.powermaster.proto.AgentServiceGrpc;
import com.aliyun.heiyu.powermaster.proto.EmptyRequest;
import com.aliyun.heiyu.powermaster.proto.EmptyReply;
import com.aliyun.heiyu.powermaster.proto.PowerCommand;
import com.aliyun.heiyu.powermaster.proto.RegisterRequest;
import com.aliyun.heiyu.powermaster.proto.ReportStatusRequest;

class AgentServiceImpl extends AgentServiceGrpc.AgentServiceImplBase {

    private static Logger log = LoggerFactory.getLogger(AgentServiceImpl.class);

    private AgentManager agentManager;

    public AgentServiceImpl(AgentManager agentManager) {
        this.agentManager = agentManager;
    }

    @Override
    public void register(RegisterRequest request, StreamObserver<EmptyReply> responseObserver) {
        log.info("register: {}", LogUtils.vaildlog(request.getId()) );
        EmptyReply.Builder reply = EmptyReply.newBuilder();

        agentManager.register(request.getId(), request.getMaxPower(), request.getMaxFreq());

        responseObserver.onNext(reply.build());
        responseObserver.onCompleted();
    }

    @Override
    public void subscribeCommands(EmptyRequest request, StreamObserver<PowerCommand> responseObserver) {
        log.info("subscribeCommands: {}",LogUtils.vaildlog(request.getId()) );

        agentManager.subscribe(request.getId(), responseObserver);
    }

    @Override
    public void reportStatus(ReportStatusRequest request, StreamObserver<EmptyReply> responseObserver) {
        log.info("reportStatus:\n{}", request);
        EmptyReply.Builder resp = EmptyReply.newBuilder();

        agentManager.update(request);

        responseObserver.onNext(resp.build());
        responseObserver.onCompleted();
    }

}
